package cn.boysoft.core.server.netty.codec;

import javax.annotation.Resource;

import org.jboss.netty.buffer.ChannelBuffer;
import org.jboss.netty.channel.Channel;
import org.jboss.netty.channel.ChannelHandlerContext;
import org.jboss.netty.handler.codec.http.HttpRequest;
import org.jboss.netty.handler.codec.oneone.OneToOneDecoder;
import org.jboss.netty.util.CharsetUtil;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.stereotype.Service;

import cn.boysoft.core.model.message.Request;
import cn.boysoft.core.parse.ParseToRequest;
import cn.boysoft.core.util.XmlUtil;
/**
 * @author 付厚俊
 * CreateTime 2013-4-4 下午5:09:32
 */
@Service(value="xmlRequestDecoder")
public class XmlRequestDecoder extends OneToOneDecoder{
	private final static Logger LOGGER = LoggerFactory.getLogger(XmlRequestDecoder.class);
	@Resource(name="parseXmlToRequest")
	ParseToRequest parseToRequest;
	@Override
	protected Object decode(ChannelHandlerContext context, Channel channel,
			Object object) throws Exception {
		    if (object instanceof HttpRequest) {
		    	HttpRequest httpRequest = (HttpRequest)object;
		    	LOGGER.debug("HttpRequest:\r\n"+XmlUtil.toXml(httpRequest));
		    	ChannelBuffer contentBuffer = httpRequest.getContent();
		    	String content = contentBuffer.toString(CharsetUtil.UTF_8);
		    	LOGGER.debug("Request Data Content:\r\n"+content);
		    	Request request = parseToRequest.parseToRequest(content);
	            return request;
	        }
	        return object;
	}
}
